package utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * @Description: 导出Excel工具类
 * @Author: syh
 * @Date: 2023/12/06/11:15
 */
public class ExportExcelUtils {

    /**
     * 执行导出功能
     * @param fileName 生成文件的路径
     * @param dataList 数据列表
     * @param fieldList 字段列表
     */
    public static void doExport(String fileName, List<List<String>> dataList,List<String> fieldList){
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet();
        //设置宽度
        sheet.setDefaultColumnWidth(50);

        //创建第一行
        Row row_1 = sheet.createRow(0);

        for (int i = 0 ; i < fieldList.size() ; i++) {
            String ele = fieldList.get(i);
            Cell cell = row_1.createCell(i);
            cell.setCellValue(ele);
            cell.setCellStyle(ExcelStyle.SheetStyle(workbook));
        }

        for (int i = 0; i < dataList.size(); i++) {
            List<String> eleList = dataList.get(i);
            Row row = sheet.createRow(i + 1);
            for (int j = 0; j < eleList.size() ; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(eleList.get(j));
            }
        }

        File excelFile = new File(fileName);
        if (excelFile.exists() && excelFile.isFile()) {
            excelFile.delete();
        }

        //输出Excel
        try {
            workbook.write(new FileOutputStream(fileName));
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
